import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class Message{
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}
@WebServlet("/message")
public class Java_1 extends HttpServlet {

    private List<Message> messageList=new ArrayList<Message>();
    private ObjectMapper objectMapper=new ObjectMapper();
    //存档
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.读取请求,转换为Java对象
        Message message=objectMapper.readValue(req.getInputStream(),Message.class);
        //2.得到Message，把message保存在服务器当中
        messageList.add(message);
        System.out.println("服务器收到 message: " + message);
        //3.返回响应
        resp.setStatus(200);
        //resp.getWriter().write("ok");

    }

    //读档
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //将内存当中的这些Message，组织为json格式，返回响应
        String str1=objectMapper.writeValueAsString(messageList);
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write(str1);
    }
}
